package com.devops.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.devops.admin.model.DOSClusterInfo;
import com.devops.admin.model.DOSClusterNamespace;
import com.devops.admin.service.DOSClusterInfoService;
import com.devops.admin.service.DOSClusterNamespaceService;
import com.devops.admin.service.DOSClusterResourceService;
import com.devops.admin.util.Assert;
import com.devops.admin.util.K8sClientUtil;
import com.devops.admin.vo.DOSClusterVo;
import com.devops.common.utils.Message;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @ClassName DOSClusterResourceServiceImpl
 * @Description TODO
 * @Author heyabo
 * @Date 2022/8/24 08:56
 * @Version 1.0
 **/
@Service
public class DOSClusterResourceServiceImpl implements DOSClusterResourceService {

    @Autowired
    private DOSClusterNamespaceService dosClusterNamespaceService;
    @Autowired
    private DOSClusterInfoService dosClusterInfoService;

    @Override
    public Message deleteIngress(DOSClusterVo clusterVo) {
        Assert.isTrue(clusterVo.getId() != null && clusterVo.getId() > 0,"集群id不能为空");
        Assert.isTrue(clusterVo.getNamespaceId() != null && clusterVo.getNamespaceId() > 0,"命名空间id不能为空");
        Assert.isTrue(StrUtil.isNotBlank(clusterVo.getIngressName()),"ingress名称不能为空");

        // 查询命名空间
        DOSClusterNamespace namespace = dosClusterNamespaceService.getById(clusterVo.getNamespaceId());
        // 查询集群的info信息
        DOSClusterInfo clusterInfo = dosClusterInfoService.getOne(Wrappers.<DOSClusterInfo>lambdaQuery()
                .eq(DOSClusterInfo::getClusterId,clusterVo.getId()));
        KubernetesClient client = K8sClientUtil.getKubernetesClient(clusterInfo.getConfigPath(),clusterInfo.getConfigContent());
        Boolean delete = !client.network().ingress().inNamespace(namespace.getNamespace()).withName(clusterVo.getIngressName()).delete().isEmpty();
        if (delete){
            return Message.ok("删除成功");
        }
        return Message.error("删除失败");
    }
}
